package com.tianji.learning.task;



import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.mapper.LearningLessonMapper;
import com.tianji.learning.service.ILearningLessonService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


@Component
@Slf4j
public class LessonTask {

    @Autowired
    private ILearningLessonService lessonService;
    /**
     * 每天定时处理过期视频
     */

    //@Scheduled(cron = "0 0 1 * * ?") //每天凌晨一点触发一次
    @Scheduled(cron = "0 0/30 * * * ?") // 每30分钟触发一次
    public void handleExpireLesson(){
        log.info("每天定时处理过期视频");
        //获取所有过期课程信息
        List<LearningLesson> learningLessons = lessonService.lambdaQuery()
                .ne(LearningLesson::getStatus,LessonStatus.EXPIRED)
                .le(LearningLesson::getExpireTime, LocalDateTime.now()).list();
        if(CollUtils.isEmpty(learningLessons)){
            return;
        }
        for (LearningLesson lesson : learningLessons) {
            lesson.setStatus(LessonStatus.EXPIRED);
        }
        boolean success = lessonService.updateBatchById(learningLessons);
        if(!success){
            throw new DbException("定时处理过期视频失败");
        }
    }
}
